using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using mas.Models;

namespace mas.ViewModels;

public partial class LogWindowViewModel : ViewModelBase,IDisposable
{
    // 原始日志集合
    private readonly ObservableCollection<LogMessage> _allLogMessages;
    
    // 过滤后的日志集合（供UI绑定）
    public ObservableCollection<LogMessage> FilteredLogMessages { get; } = new ObservableCollection<LogMessage>();
    
    // 过滤选项（自动实现PropertyChanged通知）
    [ObservableProperty] private bool _showInfoLogs = true;
    [ObservableProperty] private bool _showWarningLogs = true;
    [ObservableProperty] private bool _showErrorLogs = true;
    
    // 标记是否为过滤条件变更导致的全量更新
    private bool _isFilterChange = false;
    
    // 批处理更新定时器（每100ms更新一次UI）
    private readonly DispatcherTimer _updateTimer;
    // 标记是否需要更新UI
    private bool _isUpdatePending = false;
    // 增量更新的日志缓存
    private readonly ObservableCollection<LogMessage> _pendingLogs = new ObservableCollection<LogMessage>();
    
    public LogWindowViewModel(UdpService udpService)
    {
        _allLogMessages = udpService.LogMessages;
        
        // 初始化UI更新定时器
        _updateTimer = new DispatcherTimer
        {
            Interval = TimeSpan.FromMilliseconds(100)
        };
        _updateTimer.Tick += OnUpdateTimerTick;
        _updateTimer.Start();
        
        // 监听原始日志变化（使用同步上下文确保线程安全）
        _allLogMessages.CollectionChanged += (s, e) =>
        {
            if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems != null)
            {
                // 将新日志添加到待处理队列
                foreach (var item in e.NewItems)
                {
                    if (item is LogMessage log)
                    {
                        _pendingLogs.Add(log);
                    }
                }
                RequestUpdate();
            }
        };
        // 监听过滤选项变化
        PropertyChanged += (s, e) =>
        {
            if (e.PropertyName is nameof(ShowInfoLogs) or nameof(ShowWarningLogs) or nameof(ShowErrorLogs))
            {
                // 过滤条件变化时需要全量更新
                _pendingLogs.Clear();
                foreach (var log in _allLogMessages)
                {
                    _pendingLogs.Add(log);
                }
                // 标记为过滤条件变更，需要清空列表
                _isFilterChange = true;
                RequestUpdate();
            }
        };
        // 初始加载所有日志
        foreach (var log in _allLogMessages)
        {
            _pendingLogs.Add(log);
        }
        RequestUpdate();
    }
    
    // 请求UI更新
    private void RequestUpdate()
    {
        if (!_isUpdatePending)
        {
            _isUpdatePending = true;
            // 立即触发一次更新（如果定时器间隔内有多次请求，只会处理一次）
            _updateTimer.Stop();
            _updateTimer.Start();
        }
    }
    
    // 定时器触发：批量处理日志更新
    private void OnUpdateTimerTick(object? sender, EventArgs e)
    {
        if (_isUpdatePending)
        {
            _isUpdatePending = false;
            ApplyFilter();
        }
    }
    // 过滤应用过滤条件
    private void ApplyFilter()
    {
        if (_pendingLogs.Count == 0 && 
            (ShowInfoLogs || ShowWarningLogs || ShowErrorLogs))
        {
            return; // 无新日志且过滤条件未全关，无需更新
        }

        // 1. 过滤条件全关时清空列表
        if (!ShowInfoLogs && !ShowWarningLogs && !ShowErrorLogs)
        {
            FilteredLogMessages.Clear();
            _pendingLogs.Clear();
            return;
        }

        // 2. 增量过滤新日志
        var newLogs = _pendingLogs.Where(log => 
            (log.Level == LogLevel.Info && ShowInfoLogs) ||
            (log.Level == LogLevel.Warning && ShowWarningLogs) ||
            (log.Level == LogLevel.Error && ShowErrorLogs)
        ).OrderBy(log => log.Timestamp).ToList();

        // 3. 批量添加到UI集合
        if (newLogs.Any())
        {
            // 过滤条件变更时，强制清空现有列表
            if (_isFilterChange)
            {
                FilteredLogMessages.Clear();
                _isFilterChange = false; // 重置标记
            }
            
            foreach (var log in newLogs)
            {
                FilteredLogMessages.Add(log);
            }
            
            // 保持日志数量在合理范围
            while (FilteredLogMessages.Count > 1000)
            {
                FilteredLogMessages.RemoveAt(0);
            }
        }

        _pendingLogs.Clear();
    }
    
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (_updateTimer != null)
            {
                _updateTimer.Stop();
                _updateTimer.Tick -= OnUpdateTimerTick;
            }
        }
    }
}
